<template>
  <page-container>
    <app-card>
      <template #header>
        数据筛选
      </template>
      <el-form
        ref="form"
        :model="listParams"
        :disabled="listLoading"
        label-width="70px"
        inline
        @submit.prevent="getProductCates"
      >
        <el-form-item label="商品分类">
          <el-select
            v-model="listParams.pid"
            placeholder="请选择"
            clearable
            @change="getProductCates"
          >
            <el-option
              label="全部"
              value=""
            />
            <el-option
              v-for="item in topCategories"
              :key="item.id"
              :label="`${item.html}${item.cate_name}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="listParams.is_show"
            placeholder="请选择"
            clearable
            @change="getProductCates"
          >
            <el-option
              v-for="item in isShowConfig"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称">
          <el-input
            v-model="listParams.cate_name"
            placeholder="请输入"
            clearable
            style="width: 300px;"
          >
            <template #append>
              <el-button
                icon="el-icon-search"
                @click="getProductCates"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </app-card>
    <app-card>
      <template #header>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="formVisible = true"
        >
          添加分类
        </el-button>
      </template>
      <app-table
        :list="list"
        :list-loading="listLoading"
        :list-config="listConfig"
        :element-table-configs="{
          rowKey: 'id'
        }"
      />
    </app-card>
  </page-container>
  <rule-form
    v-model="formVisible"
    v-model:cate-item="cateItem"
    :top-categories="topCategories"
    @success="handleFormSuccess"
  />
</template>

<script lang="tsx" setup>
import { ProductCategory, ProductCategoryParams } from '@/api/types/product'
import { onMounted, reactive, ref } from 'vue'
import * as categoryApi from '@/api/product'
import { ElMessage } from 'element-plus'
import RuleForm from './components/RuleForm.vue'

const cateItem = ref<ProductCategory | null>(null)
const topCategories = ref<ProductCategory[]>([])
const formVisible = ref(false)
const list = ref<ProductCategory[]>([])
const listLoading = ref(false)
const isShowConfig = reactive([
  { label: '全部', value: '' },
  { label: '显示', value: '1' },
  { label: '隐藏', value: '0' }
])
const listConfig = reactive([
  { label: 'ID', prop: 'id', align: 'center', width: 80 },
  { label: '分类名称', prop: 'cate_name' },
  {
    label: '分类图标',
    prop: 'pic',
    formatter: (row: ProductCategory) => {
      return (
        <el-image
          style="width: 50px; height: 50px"
          src={ row.pic || './src/assets/logo_small.png' }
          fit="fill"
        ></el-image>
      )
    }
  },
  { label: '排序', prop: 'sort' },
  {
    label: '状态',
    prop: 'is_show',
    formatter: (row: ProductCategory) => {
      return (
        <el-switch
          v-model={ row.is_show }
          active-value={ 1 }
          inactive-value={ 0 }
          loading={ row.statusLoading }
          active-text="显示"
          inactive-text="隐藏"
          inline-prompt
          onChange={ () => { handleUpdateStatus(row) } }
        />
      )
    }
  },
  {
    label: '操作',
    minWidth: '120px',
    fixed: 'right',
    align: 'center',
    formatter: (row: ProductCategory) => {
      return (
        <div>
          <el-button type="text" onClick={ () => { handleUpdate(row) } }>
            编辑
          </el-button>
          <el-popconfirm
            title="确认删除吗？"
            onConfirm={ () => { handleDelete(row.id) } }
            v-slots={{
              reference: () => (
                <el-button type="text">
                  删除
                </el-button>
              )
            }}
          >
          </el-popconfirm>
        </div>
      )
    }
  }
])
const listParams = ref<ProductCategoryParams>({
  page: 1,
  limit: 10,
  is_show: '',
  pid: '',
  cate_name: ''
})

onMounted(() => {
  getProductCates()
  getProductCatesTree()
})

const getProductCates = async () => {
  listLoading.value = true
  const data = await categoryApi
    .getProductCategory(listParams.value)
    .finally(() => {
      listLoading.value = false
    })
  data.list.forEach(item => {
    item.statusLoading = false
  })
  list.value = data.list
}

const getProductCatesTree = async () => {
  const data = await categoryApi
    .getCategoryTree(0)
  topCategories.value = data
}

const handleFormSuccess = () => {
  formVisible.value = false
  getProductCates()
  getProductCatesTree()
}

const handleUpdateStatus = async (row: ProductCategory) => {
  row.statusLoading = true
  const { id, is_show: status } = row
  await categoryApi.updateCategoryStatus(id, status)
    .finally(() => {
      row.statusLoading = false
    })
  ElMessage.success(`${row.is_show ? '显示' : '隐藏'}成功`)
  getProductCates()
}

const handleUpdate = (row: ProductCategory) => {
  cateItem.value = row
  formVisible.value = true
}

const handleDelete = async (id: number) => {
  await categoryApi.removeCategory(id)
  ElMessage.success('删除成功')
  getProductCates()
  getProductCatesTree()
}

</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.demo-table-expand {
  font-size: 0;
  :deep(label) {
    width: 90px;
    color: #99a9bf;
  }
  :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
}

</style>
